<template>
  <view class="page">
    <!-- 头部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="left-section" @tap="goBack">
          <image
            src="/static/icons/left_arrow.png"
            class="back-icon"
            mode="aspectFit"
          ></image>
        </view>
        <text class="header-title">个人标签</text>
        <view class="right-section" @tap="saveTags">
          <text class="save-btn">保存</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 添加标签区域 -->
      <view class="add-tags-section">
        <view class="add-tags-header">
          <text class="add-tags-title">添加标签 ({{ selectedTags.length }}/10)</text>
          <text class="add-tags-desc">添加标签彰显你的独特个性,吸引更多优秀人才~</text>
        </view>
        
        <!-- 已选标签展示 -->
        <view class="selected-tags" v-if="selectedTags.length > 0">
          <view 
            v-for="(tag, index) in selectedTags" 
            :key="tag.id"
            class="selected-tag"
          >
            <text class="selected-tag-text">{{ tag.value }}</text>
            <view class="remove-btn" @tap="removeTag(index)">
              <text class="remove-icon">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 个人身份标签 -->
      <view class="tag-category">
        <text class="category-title">个人身份</text>
        <view class="tag-list">
          <view 
            v-for="tag in identityTags" 
            :key="tag.id"
            class="tag-item"
            :class="{ 'tag-selected': isTagSelected(tag) }"
            @tap="toggleTag(tag)"
          >
            <text class="tag-text">{{ tag.value }}</text>
          </view>
        </view>
      </view>

      <!-- 管理风格标签 -->
      <view class="tag-category">
        <text class="category-title">管理风格</text>
        <view class="tag-list">
          <view 
            v-for="tag in managementTags" 
            :key="tag.id"
            class="tag-item"
            :class="{ 'tag-selected': isTagSelected(tag) }"
            @tap="toggleTag(tag)"
          >
            <text class="tag-text">{{ tag.value }}</text>
          </view>
        </view>
      </view>

      <!-- 性格特点标签 -->
      <view class="tag-category">
        <text class="category-title">性格特点</text>
        <view class="tag-list">
          <view 
            v-for="tag in personalityTags" 
            :key="tag.id"
            class="tag-item"
            :class="{ 'tag-selected': isTagSelected(tag) }"
            @tap="toggleTag(tag)"
          >
            <text class="tag-text">{{ tag.value }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getHrInfoApi, updateCompanyUserBindInfoApi } from '@/api/user.js'
import { getDictionaryDataListByTypesApi } from '@/api/company.js'

// 标签数据
const identityTags = ref([])
const managementTags = ref([])
const personalityTags = ref([])

// 已选标签
const selectedTags = ref([])

// 获取字典数据
const getDictionaryData = async () => {
  try {
    const typeKeys = ['hr_tag_identity', 'hr_tag_management_style', 'hr_tag_personality']
    const response = await getDictionaryDataListByTypesApi(typeKeys)
    
    if (response) {
      identityTags.value = response.hr_tag_identity || []
      managementTags.value = response.hr_tag_management_style || []
      personalityTags.value = response.hr_tag_personality || []
    }
  } catch (error) {
    console.error('获取字典数据失败:', error)
    uni.showToast({
      title: '获取标签数据失败',
      icon: 'none'
    })
  }
}

// 获取HR信息
const getHrInfo = async () => {
  try {
    const response = await getHrInfoApi()
    if (response && response.hrTags) {
      // 解析已选标签
      const tagNames = response.hrTags.split(',').filter(tag => tag.trim())
      selectedTags.value = []
      
      // 在所有标签中查找匹配的标签对象
      const allTags = [...identityTags.value, ...managementTags.value, ...personalityTags.value]
      tagNames.forEach(tagName => {
        const foundTag = allTags.find(tag => tag.value === tagName.trim())
        if (foundTag) {
          selectedTags.value.push(foundTag)
        }
      })
    }
  } catch (error) {
    console.error('获取HR信息失败:', error)
  }
}

// 检查标签是否已选中
const isTagSelected = (tag) => {
  return selectedTags.value.some(selectedTag => selectedTag.id === tag.id)
}

// 切换标签选择状态
const toggleTag = (tag) => {
  if (isTagSelected(tag)) {
    // 如果已选中，则移除
    const index = selectedTags.value.findIndex(selectedTag => selectedTag.id === tag.id)
    if (index > -1) {
      selectedTags.value.splice(index, 1)
    }
  } else {
    // 如果未选中，则添加（限制最多10个）
    if (selectedTags.value.length < 10) {
      selectedTags.value.push(tag)
    } else {
      uni.showToast({
        title: '最多只能选择10个标签',
        icon: 'none'
      })
    }
  }
}

// 移除已选标签
const removeTag = (index) => {
  selectedTags.value.splice(index, 1)
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 保存标签
const saveTags = async () => {
  if (selectedTags.value.length === 0) {
    uni.showToast({
      title: '请至少选择一个标签',
      icon: 'none'
    })
    return
  }

  try {
    // 将标签转换为逗号分隔的字符串
    const tagsString = selectedTags.value.map(tag => tag.value).join(',')
    
    // 调用保存标签的API
    await updateCompanyUserBindInfoApi({
      hrTags: tagsString
    })
    
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    // 延迟返回，让用户看到成功提示
    setTimeout(() => {
      // 发送事件通知上一页需要刷新数据
      uni.$emit('refreshHrInfo')
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    console.error('保存标签失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  }
}

onMounted(async () => {
  // 先获取字典数据，再获取HR信息
  await getDictionaryData()
  await getHrInfo()
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #ffffff;
}

/* 头部导航 */
.header {
  background-color: #00bdb4;
  padding-top: var(--status-bar-height);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 88rpx;
  position: relative;
}

.left-section {
  display: flex;
  align-items: center;
  min-width: 80rpx;
  padding: 20rpx 0;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #ffffff;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.right-section {
  display: flex;
  align-items: center;
  min-width: 80rpx;
  padding: 20rpx 0;
}

.save-btn {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 内容区域 */
.content {
  padding: 40rpx 30rpx;
}

/* 添加标签区域 */
.add-tags-section {
  margin-bottom: 60rpx;
}

.add-tags-header {
  margin-bottom: 32rpx;
}

.add-tags-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #111827;
  display: block;
  margin-bottom: 16rpx;
}

.add-tags-desc {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  line-height: 1.5;
}

/* 已选标签 */
.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.selected-tag {
  display: flex;
  align-items: center;
  background-color: #dbeafe;
  color: #2563eb;
  padding: 12rpx 20rpx;
  border-radius: 9999rpx;
  font-size: 28rpx;
}

.selected-tag-text {
  margin-right: 8rpx;
}

.remove-btn {
  width: 32rpx;
  height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.remove-icon {
  font-size: 24rpx;
  font-weight: bold;
  color: #2563eb;
}

/* 标签分类 */
.tag-category {
  margin-bottom: 48rpx;
}

.category-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 24rpx;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag-item {
  padding: 16rpx 24rpx;
  border-radius: 9999rpx;
  font-size: 28rpx;
  background-color: #f3f4f6;
  color: #6b7280;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tag-item.tag-selected {
  background-color: #dbeafe;
  color: #2563eb;
}

.tag-item:active {
  transform: scale(0.95);
}

.tag-text {
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .content {
    padding: 30rpx 20rpx;
  }
  
  .add-tags-title {
    font-size: 32rpx;
  }
  
  .category-title {
    font-size: 30rpx;
  }
  
  .tag-item {
    padding: 14rpx 20rpx;
    font-size: 26rpx;
  }
}
</style>
